const app = getApp();
const util = require('../../utils/util.js');
const commonUtil = require('../../utils/common.js');
const FuturesApi = require('../../api/futures.js');
const query = wx.createSelectorQuery();

Page({
  data: {
    currentExName: '沪铜',
    currentEXChangeCode: 'SHFE',
    currentMenus: [],
    shfeList: [
      {menuName: '沪铜', itemName: '沪铜', exChangeCode: 'SHFE'},
      {menuName: '沪铝', itemName: '沪铝', exChangeCode: 'SHFE'},
      {menuName: '沪锌', itemName: '沪锌', exChangeCode: 'SHFE'},
      {menuName: '沪铅', itemName: '沪铅', exChangeCode: 'SHFE',},
      {menuName: '沪锡', itemName: '沪锡', exChangeCode: 'SHFE'},
      {menuName: '沪镍', itemName: '沪镍', exChangeCode: 'SHFE'},
    ],
    lmeList: [
      {menuName: '伦铜电3', itemName: '伦铜电3', exChangeCode: 'LME'},
      {menuName: '伦铝电3', itemName: '伦铝电3', exChangeCode: 'LME'},
      {menuName: '伦锌电3', itemName: '伦锌电3', exChangeCode: 'LME'},
      {menuName: '伦铅电3', itemName: '伦铅电3', exChangeCode: 'LME'},
      {menuName: '伦锡电3', itemName: '伦锡电3', exChangeCode: 'LME'},
      {menuName: '伦镍电3', itemName: '伦镍电3', exChangeCode: 'LME'},
    ],
    comexList: [
      {menuName: '美精铜', itemName: 'COMEX铜', exChangeCode: 'COMEX'},
    ],
    tableInfo: {
      columns: [
        {label: '名称', prop: 'exName'},
        {label: '价格区间', prop: 'priceRange'},
        {label: '最新价', prop: 'lastPrice'},
        {label: '涨跌', prop: 'upsDowns'},
        {label: '日期', prop: 'updateTime'},
      ],
      data: [],
      inFutures: true,
    },
    ws: {},
    wsData: [],
    optionsData: {
      currentMenus: null,
      currentEXChangeCode: null,
      currentExName: null
    }
  },
  onLoad(options) {
    console.log(options);
    if (options.currentEXChangeCode) {
      let _currentMenus = options.currentEXChangeCode == 'SHFE' ? this.data.shfeList : options.currentEXChangeCode == 'LME' ? this.data.lmeList : this.data.comexList;
      this.setData({
        ['optionsData.currentMenus']: _currentMenus,
        ['optionsData.currentEXChangeCode']: options.currentEXChangeCode,
        ['optionsData.currentExName']: options.currentExName,
      })
    }
  },
  onShow() {
    if (typeof this.getTabBar === 'function' &&  this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      })
    }
    // wx.removeStorageSync('newsInfo');

    if (this.data.ws && this.data.ws.readyState == 1) {
      this.data.ws.close();
    }
    this.wsInit()
    if (this.data.optionsData.currentEXChangeCode) {
      this.setData({
        currentMenus: this.data.optionsData.currentMenus,
        currentEXChangeCode: this.data.optionsData.currentEXChangeCode,
        currentExName: this.data.optionsData.currentExName,
      })
    } else {
      this.initData()
    }
    setTimeout(()=>{
      this.getFuturesContract()
    }, 200)
  },
  onHide(){
    if (this.data.ws) {
      this.data.ws.close();
    }
    this.initData()
  },
  onUnload(){
    if (this.data.ws) {
      this.data.ws.close();
    }
    this.initData()
  },
  initData() {
    this.setData({
      currentMenus: this.data.shfeList,
      currentEXChangeCode: 'SHFE',
      currentExName: '沪铜',
      ['optionsData.currentMenus']: null,
      ['optionsData.currentEXChangeCode']: null,
      ['optionsData.currentExName']: null,
    })
  },
  // 根据名称查询合约列表
  getFuturesContract(){
    FuturesApi.getFuturesContract({exName: this.data.currentExName}).then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        if (res.data.length > 0) {
          var array = res.data.map(i=>{
            if(i.quoteDate) { i.quoteDate_MD = util.formatDate(i.quoteDate, 'MM-DD') }
            else if (i.updateTime) { i.updateTime_MDHM = util.formatDate(i.updateTime, 'MM-DD HH:mm') }
            else if (i.quoteUnit) { i.quoteUnit = util.quoteUnitFilter(i.quoteUnit) }
            else if (i.commodity) { 
              i.commodityName = i.commodity.commodityName;
              i.commodityNo = i.commodity.commodityNo;
            } else if (i.lastPrice && i.lastClear) {
              i.upsDowns = this.calcUpDowns(i.lastPrice, i.lastClear)
              i.isRise = (i.lastPrice - i.lastClear) > 0 ? true : false;
            }
            return i;
          })
          this.setData({
            ['tableInfo.data']: array
          })
          let wsMsg = {'exName': this.data.currentExName};
          console.log(this.data.ws);
          if (this.data.ws.readyState == 1) {
            setTimeout(()=>{
              wx.sendSocketMessage({
                data: JSON.stringify(wsMsg),
              })
            }, 200)
          } else {
            this.wsInit()
            setTimeout(()=>{
              wx.sendSocketMessage({
                data: JSON.stringify(wsMsg),
              })
            }, 200)
          }
        }
      } else {
        if (res.errCode == '999901') {
          commonUtil.handleTokenExpire('/pages/futures/futures','tab')
        }
      }
    })
  },
  // 菜单选择
  menuClick(e){
    var code = e.currentTarget.dataset.code;
    let _currentMenus = code == 'SHFE' ? this.data.shfeList : code == 'LME' ? this.data.lmeList : this.data.comexList;
    let _currentExName = code == 'COMEX' ? _currentMenus[0].menuName : _currentMenus[0].itemName;
    this.setData({
      currentEXChangeCode: code,
      currentMenus: _currentMenus,
      currentExName: _currentExName,
    })
    query.select("#table-area").scrollLeft = 0;
    this.getFuturesContract()
  },
  // 子菜单选择
  subMenuClick(e){
    let _currentItem = e.currentTarget.dataset.item;
    this.setData({
      currentExName: _currentItem.itemName
    })
    this.getFuturesContract()
  },
  // 计算涨跌 lastPrice：最新价格 lastClear：昨日结算
  calcUpDowns(lastPrice, lastClear){
    if (lastPrice && lastClear) {
      let num = lastPrice - lastClear
      return util.bigNumberFixed(num, 2)
    } else {
      return null;
    }
  },
  wsInit(){
    const _this = this;
    this.data.ws = wx.connectSocket({
      url: app.globalData.wsUrl,
      header: {'content-type': 'aplication/json'},
      success: function(){console.log('open success');},
      fail: function(){console.log('open fail');}
    })
    wx.onSocketOpen((result) => {
      console.log("onSocketOpen");
      console.log(result);
    })
    wx.onSocketMessage((result) => {
      console.log("onSocketMessage");
      // console.log(result);
      console.log(JSON.parse(result.data));
      _this.setData({
        wsData: JSON.parse(result.data)
      })
      setTimeout(()=>{
        if (_this.data.wsData.data) {
          if (_this.data.wsData.data.dataType == 'contract') {
            let array = _this.data.tableInfo.data.map(item=>{
              let obj = _this.data.wsData.data.data.find(i=>i.exCode == item.exCode);
              if (obj) {
                item.lastClear = obj.lastClear;
                item.lastPrice = obj.lastPrice;
                item.upsDowns = _this.calcUpDowns(obj.lastPrice, obj.lastClear)
                item.isRise = (obj.lastPrice - obj.lastClear) > 0 ? true : false;
                item.updateTime = obj.updateTime.substring(5,16);
                item.updateTime_MDHM = item.updateTime;
              }
              return item;
            })
            _this.setData({
              ['tableInfo.data']: array
            })
          }
        }
      }, 200)
    })
    wx.onSocketClose((result) => {
      console.log("onSocketClose");
      console.log(result);
    })
    wx.onSocketError((result) => {
      console.log("onSocketError");
      console.log(result);
    })
  },

  onShareAppMessage() {
    // currentMenus: this.data.shfeList,
    // currentEXChangeCode: 'SHFE',
    // currentExName: '沪铜',
    console.log(this.data.currentMenus);
    console.log(this.data.currentEXChangeCode, this.data.currentExName);
    return {
      title: "期货",
      path: "/pages/futures/futures?currentExName="+this.data.currentExName+"&currentEXChangeCode="+this.data.currentEXChangeCode,
    }
  },

  onShareTimeline() {
    return {
      title: "期货",
      query: "currentExName="+this.data.currentExName+"&currentEXChangeCode="+this.data.currentEXChangeCode,
    }
  }
})